package com.wbc.smartHome.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wbc.smartHome.dao.CommodityDao;
import com.wbc.smartHome.dao.CommodityLabelDao;
import com.wbc.smartHome.model.Commodity;
import com.wbc.smartHome.model.CommodityLabel;
import com.wbc.smartHome.model.CommodityType;
import com.wbc.smartHome.model.Result;
import com.wbc.smartHome.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class CommodityService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CommodityDao commodityDao;
    private String key = "commodity";
    @Autowired
    private CommodityLabelDao commodityLabelDao;

    public PageInfo<Commodity> getCommodityList(Commodity commodity) {
       /* ListOperations listOps  = redisTemplate.opsForList();
        List<Commodity> commodityList = listOps.range(key, 0, -1);*/
        PageHelper.startPage(commodity.getPageNo(), commodity.getPageSize());
        List<Commodity> commodityList = commodityDao.getCommodityList(commodity);
        PageInfo<Commodity> pageInfo = new PageInfo<>(commodityList);
        return pageInfo;
    }


    public void setCommodity(Commodity commodity, String adminToken) {
        int adminId = JWTUtil.getAdmin(adminToken).getId();
        commodityDao.setCommodity(commodity.getName(), commodity.getImg(), commodity.getTypeId(),commodity.getNowPrice(),commodity.getFirstPrice(),commodity.getAddress(),commodity.getContent(),adminId);
        commodity.setId(commodityDao.getCommodityIdByName(commodity.getName()));
        for (CommodityLabel commodityLabel:commodity.getCommodityLabelList()){
            commodityDao.setCommodityLabel(commodityLabel.getId(),commodity.getId(),adminId);
        }
    }

    public List<Commodity> getRecommendCommodity() {
        /*ListOperations listOps  = redisTemplate.opsForList();
        List<Commodity> commodityList = listOps.range("commodity", 0, -1);*/
        List<Commodity> commodityList = commodityDao.getRecommendCommodityList();
        // 生成五个不重复的随机索引
        Set<Integer> indexSet = new HashSet<>();
        Random random = new Random();
        while (indexSet.size() < 5 && indexSet.size() < commodityList.size()) {
            indexSet.add(random.nextInt(commodityList.size()));
        }
        // 将随机索引中对应的元素存入新的ArrayList
        ArrayList<Commodity> recommendList = new ArrayList<>();
        for (Integer index : indexSet) {
            recommendList.add(commodityList.get(index));
        }
        return recommendList;
    }

    /*获取特价商品*/
    public List<Commodity> getSpecialOffer() {
        List<Commodity> commodityList = commodityDao.getSpecialOffer();
        return commodityList;
    }

    /*进入分类后的商城*/
    public List<Commodity> getCommodityListByTypeId(Integer typeId) {
        List<Commodity> commodityList = commodityDao.getCommodityListByTypeId(typeId);
        return commodityList;
    }

    /*按照id查询商品并将标签封装进属性*/
    public Commodity getCommodityById(Integer id) {
        Commodity commodity = commodityDao.getCommodityById(id);
        List<CommodityLabel> commodityLabels = commodityLabelDao.getCommodityLabelNameByCommodityId(id);
        commodity.setCommodityLabelList(commodityLabels);
        return commodity;
    }


    public List<Commodity> getCommodityListByLabelId(Integer labelId) {
         List<Commodity> commodityList = commodityDao.getCommodityListByLabelId(labelId);
         for (Commodity commodity : commodityList) {
             List<CommodityLabel> list= commodityLabelDao.getCommodityLabelNameByLabelId(labelId);
             commodity.setCommodityLabelList(list);
         }
         return commodityList;
    }
    public void deleteCLabelbyCommodityId(int commodityId) {
        commodityDao.deleteCLabelbyCommodityId(commodityId);
    }
    public void delete(int id) {
        commodityDao.delete(id);
        deleteCLabelbyCommodityId(id);
    }

    public Result uploadImg(CommonsMultipartFile commonsMultipartFile) throws IOException {
        //为了避免上传的文件重名,重新生成一个文件名
        String newFileName = new Date().getTime()+commonsMultipartFile.getOriginalFilename();
        //连接oss
        OSS ossClient = new OSSClientBuilder().build("https://"+endpoint, accessKeyId, accessKeySecret);
        //长传文件
        ossClient.putObject(bucketName, newFileName, commonsMultipartFile.getInputStream());
        //拼接文件在oss中访问地址
        String url = "https://"+bucketName+"."+endpoint+"/"+newFileName;
        //newsDao.savePhoto(url);
        return new Result(200,"操作成功",url);
    }

    public void deleteImg(String url) {
        System.out.println(url);
        String objectName = url.substring(48,url.length()-1);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("https://"+endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    public List<CommodityType> getCommodityType() {
        List<CommodityType> commodityTypeList = commodityDao.getCommodityType();
        return commodityTypeList;
    }

    public List<CommodityLabel> getCommodityLabel() {
        List<CommodityLabel> list = commodityDao.getCommodityLabel();
        return list;
    }

    public void updateCommodity(Commodity commodity, String adminToken) {
        int adminId = JWTUtil.getAdmin(adminToken).getId();
        List<CommodityLabel> commodityLabels = commodity.getCommodityLabelList();
        int commodityId = commodity.getId();
        /*删除该商品所属的标签关系*/
        commodityDao.deleteByCommoidtyId(commodityId);
        /*将新的标签关系添加进去*/
        for (CommodityLabel commodityLabel : commodityLabels) {
            commodityDao.setCommodityLabel(commodityLabel.getId(),commodityId,adminId);
        }
        /*修改数据*/
        commodityDao.updataCommodity(commodity.getName(),commodity.getTypeId(),commodity.getImg(),commodity.getAddress(),commodity.getNowPrice(),commodity.getFirstPrice(),commodity.getContent(),adminId,commodity.getId());
    }

    public List<Commodity> getCommodityPhoto() {
        List<Commodity> list = commodityDao.getCommodityPhoto();
        return list;
    }
}
